package com.flyqiu.flow.bpmn.element;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
import com.flyqiu.flow.bpmn.base.BaseProcElementNode;
import lombok.Data;
import lombok.EqualsAndHashCode;


import java.util.List;
import java.util.Map;


@Data
@EqualsAndHashCode(callSuper = true)
public abstract class ProcNodeModel extends BaseProcElement implements BaseProcElementNode {

    private JSONObject attributes;

    private String defaultTargetKey;

    @JSONField(deserialize = false, serialize = false)
    private List<SequenceFlow> ingoingFlows;

    @JSONField(deserialize = false, serialize = false)
    private List<SequenceFlow> outgoingFlows;

    public void setOutgoingFlows(List<SequenceFlow> outgoingFlows) {
        updateProcModel(this.outgoingFlows, outgoingFlows);
        this.outgoingFlows = outgoingFlows;
    }

    protected void updateProcModel(List<SequenceFlow> oldList, List<SequenceFlow> list) {
        if (processModel == null || processModel.isLock()) return;
        Map<String, BaseProcElement> elementMap = processModel.getElementMap();
        List<BaseProcElement> elements = processModel.elements;
        if (oldList != null) {
            for (SequenceFlow item : oldList) {
                elements.remove(item);
                elementMap.remove(item.getDefKey());
            }
        }
        if (list == null) return;
        for (SequenceFlow flow : list) {
            elements.add(flow);
            elementMap.put(flow.getDefKey(), flow);
        }
    }

    public void setIngoingFlows(List<SequenceFlow> ingoingFlows) {
        updateProcModel(this.outgoingFlows, outgoingFlows);
        this.ingoingFlows = ingoingFlows;

    }

    @Override
    protected void initElement(JSONObject element, ProcessModel processModel) {
    }

    @Override
    public String toString() {
        return String.format("{defKey:%s,defName:%s}", getDefKey(), getDefName());
    }

}
